import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/commons/command.dart';
import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_provider_demo/data/models/cart.dart';
import 'package:flutter_provider_demo/data/repositories/cart_repository.dart';

class CartViewModel extends ChangeNotifier {
  CartViewModel({
    required CartRepository cartRepository,
  }) : _cartRepository = cartRepository {
    loadCart = Command0(_loadCart)..execute();
  }

  final CartRepository _cartRepository;

  late Command0 loadCart;

  List<CartModel> _carts = [];

  List<CartModel> get carts => _carts;

  double get totalPrice {
    return _carts.fold(0, (previousValue, element) => previousValue + element.price);
  }

  Future<Result<void>> _loadCart() async {
    _carts = await _cartRepository.getAll();
    notifyListeners();
    return Result.ok(null);
  }
}
